package com.ybkj.o2o.sales.manager.impl;

import com.ybkj.o2o.sales.common.ActivityVo;
import com.ybkj.o2o.sales.common.CouponNumberConfig;
import com.ybkj.o2o.sales.common.DataGrid;
import com.ybkj.o2o.sales.common.api.PassengerApi;
import com.ybkj.o2o.sales.entity.Activity;
import com.ybkj.o2o.sales.entity.Activity.ActivityEvent;
import com.ybkj.o2o.sales.entity.Activity.ActivityType;
import com.ybkj.o2o.sales.entity.ActivityCouponRule;
import com.ybkj.o2o.sales.entity.ActivityRecord;
import com.ybkj.o2o.sales.entity.Coupon;
import com.ybkj.o2o.sales.entity.CouponRule;
import com.ybkj.o2o.sales.entity.passenger.Enterprise;
import com.ybkj.o2o.sales.entity.passenger.Passenger;
import com.ybkj.o2o.sales.entity.passenger.PassengerAccount;
import com.ybkj.o2o.sales.entity.passenger.PassengerAccount.PayType;
import com.ybkj.o2o.sales.manager.ActivityManager;
import com.ybkj.o2o.sales.service.ActivityCouponRuleService;
import com.ybkj.o2o.sales.service.ActivityRecordService;
import com.ybkj.o2o.sales.service.ActivityService;
import com.ybkj.o2o.sales.service.CouponRuleService;
import com.ybkj.o2o.sales.service.CouponService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class DefaultActivityManager implements ActivityManager {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private CouponRuleService couponRuleService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private ActivityCouponRuleService activityCouponRuleService;
    @Autowired
    private ActivityRecordService activityRecordService;
    @Autowired
    private PassengerApi passengerApi;

    /**
     * 创建活动.
     */
    @Transactional(rollbackFor = Exception.class)
    public Activity insert(Activity activity) {

        activityService.insert(activity);

        if (StringUtils.isNotBlank(activity.getCouponIds()) && StringUtils.isNotBlank(activity.getCouponAmounts())) {
            String[] couponIds = activity.getCouponIds().split(",");
            String[] couponAmounts = activity.getCouponAmounts().split(",");
            for (int i = 0; i < couponIds.length; i++) {
                if (StringUtils.isNotBlank(couponIds[i]) && StringUtils.isNotBlank(couponAmounts[i])) {
                    Long couponRuleId = Long.parseLong(couponIds[i]);
                    CouponRule couponRule = couponRuleService.findOne(couponRuleId, activity.getAppKey());
                    if (null != couponRule) {
                        ActivityCouponRule activityCouponRule = new ActivityCouponRule();
                        activityCouponRule.setActivityId(activity.getId());
                        activityCouponRule.setCouponRuleId(couponRule.getId());
                        activityCouponRule.setCouponRuleName(couponRule.getTitle());
                        activityCouponRule.setCouponAmount(Long.parseLong(couponAmounts[i]));
                        activityCouponRuleService.insert(activityCouponRule);
                    }
                }
            }
        }

        return activity;
    }

    /**
     * 修改活动.
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Activity activity) {

        activityService.update(activity);

    }

    /**
     * 查询单个活动.
     */
    @Override
    public Activity findOne(Long id, String appKey) {

        Activity activity = activityService.findOne(id, appKey);

        if (activity.getActivityType() != null) {

            if (null != activity && activity.getActivityType().equals(ActivityType.coupon)) {
                activity.setActivityCouponRules(activityCouponRuleService.listByActivity(activity.getId()));
            }
        }
        return activity;

    }

    /**
     * 停止活动.
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopActivity(Long activityId, String appKey) {
        activityService.stop(activityId, appKey);
    }

    /**
     * 删除活动.
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteActivity(Long activityId, String appKey) {
        activityService.delete(activityId, appKey);
    }

    /**
     * 根据活动事件查询有效活动.
     */
    @Override
    public List<Activity> listValidByEvent(String activityEvent, String appKey) {

        if (StringUtils.isNotBlank(activityEvent)) {
            return activityService.listValidByEvent(ActivityEvent.valueOf(activityEvent), appKey);
        } else {
            return activityService.listValidByEvent(null, appKey);

        }

    }

    @Override
    public List<Activity> activityList(String activityEvent, Long[] linesId, String appKey) {
        return activityService.activityList(ActivityEvent.valueOf(activityEvent), linesId, appKey);
    }

    /**
     * 分页查询活动.
     */
    @Override
    public DataGrid<Activity> queryActivities(Long companyId, String activityEvent,
                                              String activityType, Integer page, Integer size, String appKey) {

        Integer offset = 0;
        if (page != null && size != null) {
            offset = (page - 1) * size;
        }
        List<Activity> list =
                activityService.selectActivities(companyId, activityEvent, activityType, offset, size,
                        appKey);
        long count = activityService.countActivities(companyId, activityEvent, activityType, appKey);

        DataGrid<Activity> dataGrid = new DataGrid<Activity>();
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;

    }

    /**
     * 分页查询所有活动.
     */
    @Override
    public DataGrid<Activity> activityAll(Long companyId, Integer page, Integer size, String appKey) {

        Integer offset = 0;
        if (page != null && size != null) {
            offset = (page - 1) * size;
        }
        List<Activity> list = activityService.selectAllActivities(companyId, offset, size, appKey);
        long count = activityService.countAllActivities(companyId, appKey);

        DataGrid<Activity> dataGrid = new DataGrid<Activity>();
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;

    }

    /**
     * 开始活动.
     */
    @Transactional(rollbackFor = Exception.class)
    public ActivityRecord startActivity(Long activityId, Long passengerId, Long enterpriseId,
                                        String appKey) {

        Activity activity = activityService.findOne(activityId, appKey);

        Passenger passenger = passengerApi.findOnePassenger(passengerId, appKey);

        Enterprise enterprise = null;
        if (null != enterpriseId) {
            enterprise = passengerApi.findOneEnterprise(enterpriseId, appKey);
        }

        return activityRecharge(activity, passenger, enterprise, appKey);

    }

    /**
     * 开始活动V4.
     */
    @Override
    public ActivityVo startActivityV4(Long activityId, Long passengerId, Long enterpriseId, String appKey) {
        Activity activity = activityService.findOne(activityId, appKey);

        Passenger passenger = passengerApi.findOnePassenger(passengerId, appKey);

        Enterprise enterprise = null;
        if (null != enterpriseId) {
            enterprise = passengerApi.findOneEnterprise(enterpriseId, appKey);
        }

        return activityRechargeV4(activity, passenger, enterprise, appKey);
    }

    /**
     * 添加活动参与记录.
     *
     * @param activity   活动
     * @param passenger  客户
     * @param enterprise 企业客户
     * @param appKey     系统key
     * @return ActivityRecord
     */
    private ActivityRecord activityRecharge(Activity activity, Passenger passenger,
                                            Enterprise enterprise, String appKey) {

        ActivityRecord activityRecord = new ActivityRecord();
        activityRecord.setAppKey(appKey);
        activityRecord.setActivityEvent(activity.getActivityEvent());
        activityRecord.setPassengerId(passenger.getId());
        activityRecord.setPassengerName(passenger.getName());
        activityRecord.setPassengerPhone(passenger.getPhone());
        activityRecord.setActivityId(activity.getId());
        activityRecord.setCompanyId(passenger.getCompanyId());
        activityRecord.setCompanyName(passenger.getCompanyName());

        if (activity.getActivityType().equals(ActivityType.cash)) {
            if (passenger.getType().equals(0)) {
                passengerApi.createPassengerAccount(passenger, activity.getMoney(),
                        PayType.RECHARGE_TYPE_ACTIVITY, PassengerAccount.OPERATING_SYS,
                        activity.getActivityEventName() + "活动返现", null, null, null, true, appKey);
            } else if (passenger.getType().equals(1)) {
                passengerApi.createEnterpriseAccount(enterprise, activity.getMoney(),
                        PayType.RECHARGE_TYPE_ACTIVITY, PassengerAccount.OPERATING_SYS,
                        activity.getActivityEventName() + "活动返现", null, null, null, true, appKey);
                activityRecord.setEnterpriseId(enterprise.getId());
                activityRecord.setEnterpriseName(enterprise.getName());
            }
            activityRecord.setMoney(activity.getMoney());
            activityRecord.setMemo("尊敬的用户您好！欢迎您参加【" + activity.getActivityEventName()
                    + "】活动，系统已经为您的余额充值了【" + activity.getMoney() + "】元，赶快进入个人中心查看吧！更多精彩活动，即将奉献，欢迎再次参与。");
            activityRecordService.insert(activityRecord);
        } else if (activity.getActivityType().equals(ActivityType.coupon)) {
            //获取活动、优惠规则绑定表
            List<ActivityCouponRule> activityCouponRules = activityCouponRuleService.listByActivity(activity.getId());
            String memo = "";
            BigDecimal money = new BigDecimal(0);
            Integer lingquAmount_total = 0;
            String lingquAmounts = "";
            if (!CollectionUtils.isEmpty(activityCouponRules)) {
                for (ActivityCouponRule activityCouponRule : activityCouponRules) {
                    //获取优惠规则
                    CouponRule couponRule = couponRuleService.findOne(activityCouponRule.getCouponRuleId(), appKey);
                    //如果优惠规则不为空 并且 优惠规则有效 并且 优惠规则状态为使用中
                    if (null != couponRule && !couponRule.isLapsed() && couponRule.getTimeStatus().equals(CouponRule.COUPONRULE_STATUS_ONUSING)) {
                        // 优惠规则定义的优惠券总量
                        Integer totalNumber = couponRule.getNumber();
                        // 优惠规则定义的每人可领取数量
                        Integer eachLimit = couponRule.getEachLimit();
                        Integer lingquAmount = 0;
                        for (int i = 0; i < activityCouponRule.getCouponAmount(); i++) {
                            //查询该类优惠规则下优惠券的总量
                            Long db_totalNumber = couponService.countByRuleAndPassenger(couponRule.getId(), null);
                            //生成的优惠券数量 小于 规则定义的数量
                            if (db_totalNumber < totalNumber) {
                                // 查询该用户已绑定的优惠券数量
                                Long db_eachLimit = couponService.countByRuleAndPassenger(couponRule.getId(), passenger.getId());
                                //如果规则定义的每人领取数量为0（0为不限制数量） 或者 该用户已领的优惠券数量小于规则定义的每人领取数量
                                if (eachLimit == 0 || (db_eachLimit < eachLimit)) {

                                    //获取生成的该类规则优惠券总数量
                                    Long number = couponService.getRunningNumber(couponRule.getId(), appKey);
                                    if (null == number) {
                                        number = 0L;
                                    }
                                    Coupon coupon = new Coupon();
                                    coupon.setRunCode(number + 1);
                                    coupon.setCode(couponRule.getCode() + CouponNumberConfig.padZero(number + 1));
                                    coupon.setPhone(passenger.getPhone());
                                    coupon.setStatus(Coupon.COUPON_STATUS_NOTUSE);// 未用（已绑定）
                                    coupon.setCouponRuleId(couponRule.getId());
                                    coupon.setPassengerId(passenger.getId());
                                    coupon.setAppKey(appKey);
                                    couponService.insertRecord(coupon);

                                    lingquAmount++;
                                    lingquAmount_total++;
                                    if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                                        // 打折

                                    } else if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                                        // 抵扣
                                        money = money.add(couponRule.getMoney());
                                    }
                                }

                            }
                        }

                        lingquAmounts += lingquAmount + ",";

                        if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                            // 打折
                            memo +=
                                    "【" + couponRule.getTitle() + "】券" + lingquAmount + "张:"
                                            + couponRule.getDiscount() + "折";
                        } else if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                            // 抵扣
                            memo +=
                                    "【" + couponRule.getTitle() + "】券" + lingquAmount + "张:" + couponRule.getMoney()
                                            + "元";
                        }


                    }

                }
            }
            activityRecord.setMoney(money);
            activityRecord.setMemo("尊敬的用户您好！欢迎您参加【" + activity.getActivityEventName() + "】活动，恭喜您获得"
                    + memo + "，更多精彩活动，即将奉献，欢迎再次参与。");
            activityRecord.setLingquAmountTotal(lingquAmount_total);
            if (StringUtils.isNotBlank(lingquAmounts)) {
                activityRecord.setLingquAmounts(lingquAmounts.substring(0, lingquAmounts.length() - 1));
            }
            if (lingquAmount_total > 0) {
                activityRecordService.insert(activityRecord);
            }
        }
        return activityRecord;
    }

    /**
     * 添加活动参与记录V4.
     *
     * @param activity   活动
     * @param passenger  客户
     * @param enterprise 企业客户
     * @param appKey     系统key
     * @return ActivityRecord
     */
    private ActivityVo activityRechargeV4(Activity activity, Passenger passenger, Enterprise enterprise, String appKey) {

        ActivityVo activityVo = new ActivityVo();
        List<Long> couponIds = new ArrayList<Long>();
        List<String> couponNames = new ArrayList<String>();
        List<Integer> couponAmounts = new ArrayList<Integer>();

        ActivityRecord activityRecord = new ActivityRecord();
        activityRecord.setAppKey(appKey);
        activityRecord.setActivityEvent(activity.getActivityEvent());
        activityRecord.setPassengerId(passenger.getId());
        activityRecord.setPassengerName(passenger.getName());
        activityRecord.setPassengerPhone(passenger.getPhone());
        activityRecord.setActivityId(activity.getId());
        activityRecord.setCompanyId(passenger.getCompanyId());
        activityRecord.setCompanyName(passenger.getCompanyName());

        if (activity.getActivityType().equals(ActivityType.cash)) {
            if (passenger.getType().equals(0)) {
                passengerApi.createPassengerAccount(passenger, activity.getMoney(),
                        PayType.RECHARGE_TYPE_ACTIVITY, PassengerAccount.OPERATING_SYS,
                        activity.getActivityEventName() + "活动返现", null, null, null, true, appKey);
            } else if (passenger.getType().equals(1)) {
                passengerApi.createEnterpriseAccount(enterprise, activity.getMoney(),
                        PayType.RECHARGE_TYPE_ACTIVITY, PassengerAccount.OPERATING_SYS,
                        activity.getActivityEventName() + "活动返现", null, null, null, true, appKey);
                activityRecord.setEnterpriseId(enterprise.getId());
                activityRecord.setEnterpriseName(enterprise.getName());
            }
            activityRecord.setMoney(activity.getMoney());
            activityRecord.setMemo("尊敬的用户您好！欢迎您参加【" + activity.getActivityEventName()
                    + "】活动，系统已经为您的余额充值了【" + activity.getMoney() + "】元，赶快进入个人中心查看吧！更多精彩活动，即将奉献，欢迎再次参与。");
            activityRecordService.insert(activityRecord);
        }
        else if (activity.getActivityType().equals(ActivityType.coupon)) {
            //获取活动、优惠规则绑定表
            List<ActivityCouponRule> activityCouponRules = activityCouponRuleService.listByActivity(activity.getId());
            String memo = "";
            BigDecimal money = new BigDecimal(0);
            Integer lingquAmount_total = 0;
            String lingquAmounts = "";
            if (!CollectionUtils.isEmpty(activityCouponRules)) {
                for (ActivityCouponRule activityCouponRule : activityCouponRules) {
                    //获取优惠规则
                    CouponRule couponRule = couponRuleService.findOne(activityCouponRule.getCouponRuleId(), appKey);
                    //如果优惠规则不为空 并且 优惠规则有效 并且 优惠规则状态为使用中
                    if (null != couponRule && !couponRule.isLapsed() && couponRule.getTimeStatus().equals(CouponRule.COUPONRULE_STATUS_ONUSING)) {
                        // 优惠规则定义的优惠券总量
                        Integer totalNumber = couponRule.getNumber();
                        // 优惠规则定义的每人可领取数量
                        Integer eachLimit = couponRule.getEachLimit();
                        Integer lingquAmount = 0;
                        for (int i = 0; i < activityCouponRule.getCouponAmount(); i++) {
                            //查询该类优惠规则下优惠券的总量
                            Long db_totalNumber = couponService.countByRuleAndPassenger(couponRule.getId(), null);
//                            if (ActivityEvent.newRegister.equals(activity.getActivityEvent())) {
//                                db_totalNumber = couponService.countByRuleAndPassengerGroup(couponRule.getId(), passenger.getId());
//                                if (null == db_totalNumber) {
//                                    db_totalNumber = 0l;
//                                }
//                            }
                            //生成的优惠券数量 小于 规则定义的数量
                            if (db_totalNumber <= totalNumber) {
                                // 查询该用户已绑定的优惠券数量
                                Long db_eachLimit = couponService.countByRuleAndPassenger(couponRule.getId(), passenger.getId());
                                //如果规则定义的每人领取数量为0（0为不限制数量） 或者 该用户已领的优惠券数量小于规则定义的每人领取数量
                                if (eachLimit == 0 || (db_eachLimit < eachLimit)) {
                                    //获取生成的该类规则优惠券总数量
                                    Long number = couponService.getRunningNumber(couponRule.getId(), appKey);
                                    if (null == number) {
                                        number = 0L;
                                    }
                                    Coupon coupon = new Coupon();
                                    if(null != couponRule.getDiscount()){
                                        coupon.setCouponDiscount(couponRule.getDiscount());
                                    }
                                    if(null != couponRule.getMoney()){
                                        coupon.setCouponPrice(couponRule.getMoney());
                                    }
                                    coupon.setRunCode(number + 1);
                                    coupon.setCode(couponRule.getCode() + CouponNumberConfig.padZero(number + 1));
                                    coupon.setCouponRuleId(couponRule.getId());
                                    coupon.setPhone(passenger.getPhone());
                                    coupon.setStatus(Coupon.COUPON_STATUS_NOTUSE);// 未用（已绑定）
                                    coupon.setPassengerId(passenger.getId());
                                    coupon.setAppKey(appKey);
                                    //没有线路限制的为null
                                    coupon.setLineId(null);
                                    couponService.insertRecord(coupon);

                                    lingquAmount++;
                                    lingquAmount_total++;
                                    if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                                        // 打折

                                    } else if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                                        // 抵扣
                                        money = money.add(couponRule.getMoney());
                                    }

                                }
                            }
                        }
                        lingquAmounts += lingquAmount + ",";

                        if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                            // 打折
                            memo +=
                                    "【" + couponRule.getTitle() + "】券" + lingquAmount + "张:"
                                            + couponRule.getDiscount() + "折";
                        } else if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                            // 抵扣
                            memo +=
                                    "【" + couponRule.getTitle() + "】券" + lingquAmount + "张:" + couponRule.getMoney()
                                            + "元";
                        }

                        couponIds.add(couponRule.getId());
                        couponNames.add(couponRule.getTitle());
                        couponAmounts.add(lingquAmount);

                    }

                }
            }
            activityRecord.setMoney(money);
            activityRecord.setMemo("尊敬的用户您好！欢迎您参加【" + activity.getActivityEventName() + "】活动，恭喜您获得"
                    + memo + "，更多精彩活动，即将奉献，欢迎再次参与。");
            activityRecord.setLingquAmountTotal(lingquAmount_total);
            if (StringUtils.isNotBlank(lingquAmounts)) {
                activityRecord.setLingquAmounts(lingquAmounts.substring(0, lingquAmounts.length() - 1));
            }
            if (lingquAmount_total > 0) {
                activityRecordService.insert(activityRecord);
            }
        }

        activityVo.setActivityRecord(activityRecord);
        activityVo.setActivityType(activity.getActivityType());
        activityVo.setMoney(activity.getMoney());
        activityVo.setCouponIds(couponIds);
        activityVo.setCouponNames(couponNames);
        activityVo.setCouponAmounts(couponAmounts);

        return activityVo;
    }

    /**
     * 根据公司id查询首单免费活动.
     */
    @Override
    public List<Activity> findOneFreeActivity(Long companyId, String appKey) {
        return activityService.findOneFreeActivity(companyId, Activity.ActivityEvent.firstOrderFree,
                appKey);
    }


}
